﻿/*
 * Toast8
 * All rights reserved
 * Copyright (C) 2014 Peter Nylander
 */
using Microsoft.WindowsAPICodePack.Shell.PropertySystem;
using MS.WindowsAPICodePack.Internal;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Toast8.ShellHelpers;
using Windows.UI.Notifications;

namespace Toast8
{
    // Add IToastNotifier that this class should implement, each class implementing this can show different kind of toasts
    class ToastHelper
    {
        private const String APP_ID = "Toast81";

        private static string toastImageAndText03Template = "<toast>"
                                        + "<audio silent='{0}'/>"
                                        + "<visual version='1'>"
                                            + "<binding template='ToastImageAndText02'>"
                                                + "<image id='1' src='{1}' alt='Toast8.png'/>"
                                                + "<text id='1'>{2}</text>"
                                                + "<text id='2'>{3}</text>"
                                            + "</binding>"
                                        + "</visual>"
                                    + "</toast>";

        public static void ShowToastNotification(bool silent, string imageUri, string heading, string text1, string text2)
        {
            try
            {
                String imagePath = string.Empty;
                if (!string.IsNullOrEmpty(imageUri) && !imageUri.StartsWith("http"))
                {
                    imagePath = "file:///" + Path.GetFullPath(imageUri);
                }

                string toastString = string.Format(toastImageAndText03Template, silent.ToString().ToLower(), imagePath, heading, text1, text2);

                Windows.Data.Xml.Dom.XmlDocument toastXml = new Windows.Data.Xml.Dom.XmlDocument();
                toastXml.LoadXml(toastString);

                // Create the toast and attach event listeners
                ToastNotification toast = new ToastNotification(toastXml);
                toast.Activated += ToastActivated;
                toast.Dismissed += ToastDismissed;
                toast.Failed += ToastFailed;
                toast.ExpirationTime = DateTimeOffset.UtcNow.AddSeconds(5);

                // Show the toast. Be sure to specify the AppUserModelId on your application's shortcut!
                ToastNotificationManager.CreateToastNotifier(APP_ID).Show(toast);
            }
            catch (Exception)
            {
                throw;
            }

        }

        private static void ToastActivated(ToastNotification sender, object e)
        {
            // Show player
            //Spotify.SendAction(SpotifyAction.ShowSpotify);
            Debug.WriteLine("The user activated the toast.");
        }

        private static void ToastDismissed(ToastNotification sender, ToastDismissedEventArgs e)
        {
            String outputText = "";
            switch (e.Reason)
            {
                case ToastDismissalReason.ApplicationHidden:
                    outputText = "The app hid the toast using ToastNotifier.Hide";
                    break;
                case ToastDismissalReason.UserCanceled:
                    outputText = "The user dismissed the toast";
                    break;
                case ToastDismissalReason.TimedOut:
                    outputText = "The toast has timed out";
                    break;
            }


            Debug.WriteLine(outputText);
        }

        private static void ToastFailed(ToastNotification sender, ToastFailedEventArgs e)
        {
            Debug.WriteLine("The toast encountered an error." + e.ErrorCode);
        }

        /// <summary>
        /// In order to display toasts, a desktop application must have a shortcut on the Start menu.
        /// Also, an AppUserModelID must be set on that shortcut.
        /// </summary>
        /// <remarks>
        /// The shortcut should be created as part of the installer. The following code shows how to create
        /// a shortcut and assign an AppUserModelID using Windows APIs. You must download and include the 
        /// Windows API Code Pack for Microsoft .NET Framework for this code to function
        /// 
        /// Included in this project is a wxs file that be used with the WiX toolkit
        /// to make an installer that creates the necessary shortcut. One or the other should be used.
        /// </remarks>
        /// <returns></returns>
        public static bool TryCreateShortcut()
        {
            String shortcutPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\Microsoft\\Windows\\Start Menu\\Programs\\" + APP_ID + ".lnk";
            if (!File.Exists(shortcutPath))
            {
                InstallShortcut(shortcutPath);
                return true;
            }
            return false;
        }

        private static void InstallShortcut(String shortcutPath)
        {
            // Find the path to the current executable
            String exePath = Process.GetCurrentProcess().MainModule.FileName;
            IShellLinkW newShortcut = (IShellLinkW)new CShellLink();

            // Create a shortcut to the exe
            ShellHelpers.ErrorHelper.VerifySucceeded(newShortcut.SetPath(exePath));
            ShellHelpers.ErrorHelper.VerifySucceeded(newShortcut.SetArguments(""));

            // Open the shortcut property store, set the AppUserModelId property
            IPropertyStore newShortcutProperties = (IPropertyStore)newShortcut;

            using (PropVariant appId = new PropVariant(APP_ID))
            {
                ShellHelpers.ErrorHelper.VerifySucceeded(newShortcutProperties.SetValue(SystemProperties.System.AppUserModel.ID, appId));
                ShellHelpers.ErrorHelper.VerifySucceeded(newShortcutProperties.Commit());
            }

            // Commit the shortcut to disk
            IPersistFile newShortcutSave = (IPersistFile)newShortcut;

            ShellHelpers.ErrorHelper.VerifySucceeded(newShortcutSave.Save(shortcutPath, true));
        }
    }
}
